<html lang="en-US">

<head>
    
<title>迷惑了，Go len() 是怎么计算出来的？ - 花落雨忧</title>

<meta property="og:title" content="迷惑了，Go len() 是怎么计算出来的？ - 花落雨忧">



    



    
    <meta property="description" content="大家好，我是煎鱼。
最近看到了一个很有意思的话题，我们平时常常会用 Go 的内置函数 len 去获取各种 map、slice 的长度，那他是怎么实现的呢？
正当我想去看看 len 的具体实现时，一展身手，却发现竟然是个空方法：
[&amp;hellip;] func len(v Type) int 看注解也没有 link 到其他 runtime 函数，那么 len 函数是如何被调用的呢？ &amp;hellip;">
    <meta property="og:description" content="大家好，我是煎鱼。
最近看到了一个很有意思的话题，我们平时常常会用 Go 的内置函数 len 去获取各种 map、slice 的长度，那他是怎么实现的呢？
正当我想去看看 len 的具体实现时，一展身手，却发现竟然是个空方法：
[&amp;hellip;] func len(v Type) int 看注解也没有 link 到其他 runtime 函数，那么 len 函数是如何被调用的呢？ &amp;hellip;">
    






<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1">

<link rel="shortcut icon" href="https://www.lican.asia/logo/logo.png" type="image/x-icon" />



<link rel="stylesheet" href="/css/style.min.css" />

<link rel="stylesheet" href="/css/reset.min.css" />




<script src="https://www.lican.asia/js/highlight.min.js"></script>

<script>
hljs.configure({ ignoreUnescapedHTML: true })
hljs.highlightAll();
</script>


<script src="https://www.lican.asia/js/jquery.min.js"></script>




<link href="https://www.lican.asia/css/hugo-code.min.css" rel="stylesheet" />



    <style>
        .post-content img {
            max-width: 400px;
        }
    </style>
</head>

<body id="period" class="home blog">
    <a class="skip-content" href="#main">Press "Enter" to skip to content</a>
    <div id="overflow-container" class="overflow-container">
        <header class="site-header" id="site-header" role="banner">
    <div class="max-width">
        <div id="title-container" class="title-container">
            <div id="site-title" class="site-title"><a href="/">花落雨忧</a></div>
            <p class="tagline">思所及 力所行 方为真.</p>
        </div>
        
        <div id="menu-primary-container" class="menu-primary-container">
            <div class="icon-container">
            </div>
            <div id="menu-primary" class="menu-container menu-primary" role="navigation">
                <nav class="menu">
                    <ul id="menu-primary-items" class="menu-primary-items">
                        
                        
                        <li id="menu-item-0"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/posts" aria-current="page" tabindex="0">首页</a></li>
                        
                        <li id="menu-item-1"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/tech/" aria-current="page" tabindex="1">技术文档</a></li>
                        
                        <li id="menu-item-2"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/article/" aria-current="page" tabindex="2">文章</a></li>
                        
                        <li id="menu-item-3"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/project/" aria-current="page" tabindex="3">项目</a></li>
                        
                        <li id="menu-item-4"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/about/" aria-current="page" tabindex="4">关于</a></li>
                        
                    </ul>
                </nav>
            </div>
        </div>
    </div>
</header>

        <div id="primary-container" class="primary-container">
            <div class="max-width">
                <section id="main" class="main" role="main">
                    <div id="loop-container" class="loop-container">
                        <div
                            class="post type-post status-publish format-standard hentry entry">
                            <article>
                                <div class="post-container">
                                    <div class="post-header">
                                        <h2 class="post-title">
                                            <a href="/posts/posts/go/len/">迷惑了，Go len() 是怎么计算出来的？</a>
                                        </h2>
                                        
                                        <div class="post-byline">Published on
                                            <a class="date" href="javascript:;">2021/12/31</a>
                                            
                                            
                                            
                                            
                                            
                                        
                                    </div>
                                    <div class="post-content">
                                        <p>大家好，我是煎鱼。</p>
<p>最近看到了一个很有意思的话题，我们平时常常会用 Go 的内置函数 <code>len</code> 去获取各种 map、slice 的长度，那他是怎么实现的呢？</p>
<p>正当我想去看看 <code>len</code> 的具体实现时，一展身手，却发现竟然是个空方法：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-golang" data-lang="golang"><span style="display:flex;"><span><span style="color:#66d9ef">func</span> len(<span style="color:#a6e22e">v</span> <span style="color:#a6e22e">Type</span>) <span style="color:#66d9ef">int</span>
</span></span></code></pre></div><p>看注解也没有 link 到其他 runtime 函数，那么 len 函数是如何被调用的呢？</p>
<p>先前看国外讨论 Go 计算 len 的文章时做了一些翻译和笔记（底下有参考链接），在此分享给大家，共同进步。</p>
<h2 id="谜底">谜底</h2>
<p>今天就由煎鱼带大家一同解开这个谜底。既然是谜底，那就一开始就揭开。</p>
<p>其实 Go 语言中并没有 len 函数的具体实现代码，他其实<strong>是 Go 编译器的 &ldquo;魔法&rdquo; ，不是实际的函数调用</strong>。</p>
<p>接下来将展开这部分，我们可以更深入地了解 Go 编译器的内部工作原理。</p>
<h2 id="编译器">编译器</h2>
<p>在 Go 编译器编译时会解析命令行参数中指定的标志和 Go 源文件，对解析后的 Go 包进行类型检查，将函数编译为机器代码。代码，最后将编译后的包定义写到磁盘上。</p>
<p>内部定义基本类型、内置函数和操作函数的阶段是在 types/universe.go 当中。同时会进行内置函数和具体的操作符匹配，可以明确知道内置函数 len 对应的是 OLEN：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-golang" data-lang="golang"><span style="display:flex;"><span><span style="color:#66d9ef">var</span> <span style="color:#a6e22e">builtinFuncs</span> = [<span style="color:#f92672">...</span>]<span style="color:#66d9ef">struct</span> {
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">name</span> <span style="color:#66d9ef">string</span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">op</span>   <span style="color:#a6e22e">Op</span>
</span></span><span style="display:flex;"><span>}{
</span></span><span style="display:flex;"><span>	{<span style="color:#e6db74">&#34;append&#34;</span>, <span style="color:#a6e22e">OAPPEND</span>},
</span></span><span style="display:flex;"><span>	{<span style="color:#e6db74">&#34;cap&#34;</span>, <span style="color:#a6e22e">OCAP</span>},
</span></span><span style="display:flex;"><span>	{<span style="color:#e6db74">&#34;close&#34;</span>, <span style="color:#a6e22e">OCLOSE</span>},
</span></span><span style="display:flex;"><span>	{<span style="color:#e6db74">&#34;complex&#34;</span>, <span style="color:#a6e22e">OCOMPLEX</span>},
</span></span><span style="display:flex;"><span>	{<span style="color:#e6db74">&#34;copy&#34;</span>, <span style="color:#a6e22e">OCOPY</span>},
</span></span><span style="display:flex;"><span>	{<span style="color:#e6db74">&#34;delete&#34;</span>, <span style="color:#a6e22e">ODELETE</span>},
</span></span><span style="display:flex;"><span>	{<span style="color:#e6db74">&#34;imag&#34;</span>, <span style="color:#a6e22e">OIMAG</span>},
</span></span><span style="display:flex;"><span>	{<span style="color:#e6db74">&#34;len&#34;</span>, <span style="color:#a6e22e">OLEN</span>},
</span></span><span style="display:flex;"><span>	<span style="color:#f92672">...</span>
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>在编译时，上分为五个阶段进行类型检查：</p>
<ul>
<li>第一阶段：常量、类型、以及函数的名称和类型。</li>
<li>第二阶段：变量赋值、接口赋值、别名声明。</li>
<li>第三阶段：类型检查函数体。</li>
<li>第四阶段：检查外部声明。</li>
<li>第五阶段：检查类型的地图键，未使用的导入。</li>
</ul>
<p>如果最后一个类型检查阶段遇到 len 函数，就会转换为 UnaryExpr 类型，一个 UnaryExpr 节点代表一个单数表达式，也最终就是不会成为函数调用：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-golang" data-lang="golang"><span style="display:flex;"><span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">typecheck1</span>(<span style="color:#a6e22e">n</span> <span style="color:#a6e22e">ir</span>.<span style="color:#a6e22e">Node</span>, <span style="color:#a6e22e">top</span> <span style="color:#66d9ef">int</span>) <span style="color:#a6e22e">ir</span>.<span style="color:#a6e22e">Node</span> {
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">n</span>, <span style="color:#a6e22e">ok</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">n</span>.(<span style="color:#f92672">*</span><span style="color:#a6e22e">ir</span>.<span style="color:#a6e22e">Name</span>); <span style="color:#a6e22e">ok</span> {
</span></span><span style="display:flex;"><span>		<span style="color:#a6e22e">typecheckdef</span>(<span style="color:#a6e22e">n</span>)
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">switch</span> <span style="color:#a6e22e">n</span>.<span style="color:#a6e22e">Op</span>() {
</span></span><span style="display:flex;"><span>	<span style="color:#f92672">...</span>
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">case</span> <span style="color:#a6e22e">ir</span>.<span style="color:#a6e22e">OCAP</span>, <span style="color:#a6e22e">ir</span>.<span style="color:#a6e22e">OLEN</span>:
</span></span><span style="display:flex;"><span>		<span style="color:#a6e22e">n</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">n</span>.(<span style="color:#f92672">*</span><span style="color:#a6e22e">ir</span>.<span style="color:#a6e22e">UnaryExpr</span>)
</span></span><span style="display:flex;"><span>		<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">tcLenCap</span>(<span style="color:#a6e22e">n</span>)
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>在调用 <code>*ir.UnaryExpr</code> 转换完毕后，会调用 <code>tcLenCap</code>，也就是 typecheck，使用 okforlen 数组来验证参数的合法性或发出相关错误信息：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-golang" data-lang="golang"><span style="display:flex;"><span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">tcLenCap</span>(<span style="color:#a6e22e">n</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">ir</span>.<span style="color:#a6e22e">UnaryExpr</span>) <span style="color:#a6e22e">ir</span>.<span style="color:#a6e22e">Node</span> {
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">n</span>.<span style="color:#a6e22e">X</span> = <span style="color:#a6e22e">Expr</span>(<span style="color:#a6e22e">n</span>.<span style="color:#a6e22e">X</span>)
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">n</span>.<span style="color:#a6e22e">X</span> = <span style="color:#a6e22e">DefaultLit</span>(<span style="color:#a6e22e">n</span>.<span style="color:#a6e22e">X</span>, <span style="color:#66d9ef">nil</span>)
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">n</span>.<span style="color:#a6e22e">X</span> = <span style="color:#a6e22e">implicitstar</span>(<span style="color:#a6e22e">n</span>.<span style="color:#a6e22e">X</span>)
</span></span><span style="display:flex;"><span>	<span style="color:#f92672">...</span>
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">var</span> <span style="color:#a6e22e">ok</span> <span style="color:#66d9ef">bool</span>
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">n</span>.<span style="color:#a6e22e">Op</span>() <span style="color:#f92672">==</span> <span style="color:#a6e22e">ir</span>.<span style="color:#a6e22e">OLEN</span> {
</span></span><span style="display:flex;"><span>		<span style="color:#a6e22e">ok</span> = <span style="color:#a6e22e">okforlen</span>[<span style="color:#a6e22e">t</span>.<span style="color:#a6e22e">Kind</span>()]
</span></span><span style="display:flex;"><span>	} <span style="color:#66d9ef">else</span> {
</span></span><span style="display:flex;"><span>		<span style="color:#a6e22e">ok</span> = <span style="color:#a6e22e">okforcap</span>[<span style="color:#a6e22e">t</span>.<span style="color:#a6e22e">Kind</span>()]
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>  
</span></span><span style="display:flex;"><span>	<span style="color:#f92672">...</span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">n</span>.<span style="color:#a6e22e">SetType</span>(<span style="color:#a6e22e">types</span>.<span style="color:#a6e22e">Types</span>[<span style="color:#a6e22e">types</span>.<span style="color:#a6e22e">TINT</span>])
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">n</span>
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>经历过上面的步骤后在对所有内容进行类型检查后，所有函数都将排队等待编译：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-golang" data-lang="golang"><span style="display:flex;"><span>	<span style="color:#a6e22e">base</span>.<span style="color:#a6e22e">Timer</span>.<span style="color:#a6e22e">Start</span>(<span style="color:#e6db74">&#34;be&#34;</span>, <span style="color:#e6db74">&#34;compilefuncs&#34;</span>)
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">fcount</span> <span style="color:#f92672">:=</span> int64(<span style="color:#ae81ff">0</span>)
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">for</span> <span style="color:#a6e22e">i</span> <span style="color:#f92672">:=</span> <span style="color:#ae81ff">0</span>; <span style="color:#a6e22e">i</span> &lt; len(<span style="color:#a6e22e">typecheck</span>.<span style="color:#a6e22e">Target</span>.<span style="color:#a6e22e">Decls</span>); <span style="color:#a6e22e">i</span><span style="color:#f92672">++</span> {
</span></span><span style="display:flex;"><span>		<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">fn</span>, <span style="color:#a6e22e">ok</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">typecheck</span>.<span style="color:#a6e22e">Target</span>.<span style="color:#a6e22e">Decls</span>[<span style="color:#a6e22e">i</span>].(<span style="color:#f92672">*</span><span style="color:#a6e22e">ir</span>.<span style="color:#a6e22e">Func</span>); <span style="color:#a6e22e">ok</span> {
</span></span><span style="display:flex;"><span>			<span style="color:#a6e22e">enqueueFunc</span>(<span style="color:#a6e22e">fn</span>)
</span></span><span style="display:flex;"><span>			<span style="color:#a6e22e">fcount</span><span style="color:#f92672">++</span>
</span></span><span style="display:flex;"><span>		}
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">base</span>.<span style="color:#a6e22e">Timer</span>.<span style="color:#a6e22e">AddEvent</span>(<span style="color:#a6e22e">fcount</span>, <span style="color:#e6db74">&#34;funcs&#34;</span>)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">compileFunctions</span>()
</span></span></code></pre></div><p>在经过在 buildssa 和 genssa 之后，再深入几层，就会将 AST 树中的 len 表达式转换为 SSA。接着我们就可以看到 Go 语言中的每种类型的长度是怎么获取的。</p>
<p>这块的处理对应 internal/ssagen/ssa.go 的 expr 方法，如下：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-golang" data-lang="golang"><span style="display:flex;"><span>	<span style="color:#66d9ef">case</span> <span style="color:#a6e22e">ir</span>.<span style="color:#a6e22e">OLEN</span>, <span style="color:#a6e22e">ir</span>.<span style="color:#a6e22e">OCAP</span>:
</span></span><span style="display:flex;"><span>		<span style="color:#a6e22e">n</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">n</span>.(<span style="color:#f92672">*</span><span style="color:#a6e22e">ir</span>.<span style="color:#a6e22e">UnaryExpr</span>)
</span></span><span style="display:flex;"><span>		<span style="color:#66d9ef">switch</span> {
</span></span><span style="display:flex;"><span>		<span style="color:#66d9ef">case</span> <span style="color:#a6e22e">n</span>.<span style="color:#a6e22e">X</span>.<span style="color:#a6e22e">Type</span>().<span style="color:#a6e22e">IsSlice</span>():
</span></span><span style="display:flex;"><span>			<span style="color:#a6e22e">op</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">ssa</span>.<span style="color:#a6e22e">OpSliceLen</span>
</span></span><span style="display:flex;"><span>			<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">n</span>.<span style="color:#a6e22e">Op</span>() <span style="color:#f92672">==</span> <span style="color:#a6e22e">ir</span>.<span style="color:#a6e22e">OCAP</span> {
</span></span><span style="display:flex;"><span>				<span style="color:#a6e22e">op</span> = <span style="color:#a6e22e">ssa</span>.<span style="color:#a6e22e">OpSliceCap</span>
</span></span><span style="display:flex;"><span>			}
</span></span><span style="display:flex;"><span>			<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">s</span>.<span style="color:#a6e22e">newValue1</span>(<span style="color:#a6e22e">op</span>, <span style="color:#a6e22e">types</span>.<span style="color:#a6e22e">Types</span>[<span style="color:#a6e22e">types</span>.<span style="color:#a6e22e">TINT</span>], <span style="color:#a6e22e">s</span>.<span style="color:#a6e22e">expr</span>(<span style="color:#a6e22e">n</span>.<span style="color:#a6e22e">X</span>))
</span></span><span style="display:flex;"><span>		<span style="color:#66d9ef">case</span> <span style="color:#a6e22e">n</span>.<span style="color:#a6e22e">X</span>.<span style="color:#a6e22e">Type</span>().<span style="color:#a6e22e">IsString</span>(): <span style="color:#75715e">// string; not reachable for OCAP
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>			<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">s</span>.<span style="color:#a6e22e">newValue1</span>(<span style="color:#a6e22e">ssa</span>.<span style="color:#a6e22e">OpStringLen</span>, <span style="color:#a6e22e">types</span>.<span style="color:#a6e22e">Types</span>[<span style="color:#a6e22e">types</span>.<span style="color:#a6e22e">TINT</span>], <span style="color:#a6e22e">s</span>.<span style="color:#a6e22e">expr</span>(<span style="color:#a6e22e">n</span>.<span style="color:#a6e22e">X</span>))
</span></span><span style="display:flex;"><span>		<span style="color:#66d9ef">case</span> <span style="color:#a6e22e">n</span>.<span style="color:#a6e22e">X</span>.<span style="color:#a6e22e">Type</span>().<span style="color:#a6e22e">IsMap</span>(), <span style="color:#a6e22e">n</span>.<span style="color:#a6e22e">X</span>.<span style="color:#a6e22e">Type</span>().<span style="color:#a6e22e">IsChan</span>():
</span></span><span style="display:flex;"><span>			<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">s</span>.<span style="color:#a6e22e">referenceTypeBuiltin</span>(<span style="color:#a6e22e">n</span>, <span style="color:#a6e22e">s</span>.<span style="color:#a6e22e">expr</span>(<span style="color:#a6e22e">n</span>.<span style="color:#a6e22e">X</span>))
</span></span><span style="display:flex;"><span>		<span style="color:#66d9ef">default</span>: <span style="color:#75715e">// array
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>			<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">s</span>.<span style="color:#a6e22e">constInt</span>(<span style="color:#a6e22e">types</span>.<span style="color:#a6e22e">Types</span>[<span style="color:#a6e22e">types</span>.<span style="color:#a6e22e">TINT</span>], <span style="color:#a6e22e">n</span>.<span style="color:#a6e22e">X</span>.<span style="color:#a6e22e">Type</span>().<span style="color:#a6e22e">NumElem</span>())
</span></span><span style="display:flex;"><span>		}
</span></span></code></pre></div><p>若是数组（array）类型，则会调用 <code>NumElem</code> 方法来获取长度值：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-golang" data-lang="golang"><span style="display:flex;"><span><span style="color:#66d9ef">type</span> <span style="color:#a6e22e">Array</span> <span style="color:#66d9ef">struct</span> {
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">Elem</span>  <span style="color:#f92672">*</span><span style="color:#a6e22e">Type</span> 
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">Bound</span> <span style="color:#66d9ef">int64</span> 
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">func</span> (<span style="color:#a6e22e">t</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">Type</span>) <span style="color:#a6e22e">NumElem</span>() <span style="color:#66d9ef">int64</span> {
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">t</span>.<span style="color:#a6e22e">wantEtype</span>(<span style="color:#a6e22e">TARRAY</span>)
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">t</span>.<span style="color:#a6e22e">Extra</span>.(<span style="color:#f92672">*</span><span style="color:#a6e22e">Array</span>).<span style="color:#a6e22e">Bound</span>
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>若是字典（map）类型或通道（channel），将会调用 <code>referenceTypeBuiltin</code> 方法：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-golang" data-lang="golang"><span style="display:flex;"><span><span style="color:#66d9ef">func</span> (<span style="color:#a6e22e">s</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">state</span>) <span style="color:#a6e22e">referenceTypeBuiltin</span>(<span style="color:#a6e22e">n</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">ir</span>.<span style="color:#a6e22e">UnaryExpr</span>, <span style="color:#a6e22e">x</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">ssa</span>.<span style="color:#a6e22e">Value</span>) <span style="color:#f92672">*</span><span style="color:#a6e22e">ssa</span>.<span style="color:#a6e22e">Value</span> {
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">lenType</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">n</span>.<span style="color:#a6e22e">Type</span>()
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">nilValue</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">s</span>.<span style="color:#a6e22e">constNil</span>(<span style="color:#a6e22e">types</span>.<span style="color:#a6e22e">Types</span>[<span style="color:#a6e22e">types</span>.<span style="color:#a6e22e">TUINTPTR</span>])
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">cmp</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">s</span>.<span style="color:#a6e22e">newValue2</span>(<span style="color:#a6e22e">ssa</span>.<span style="color:#a6e22e">OpEqPtr</span>, <span style="color:#a6e22e">types</span>.<span style="color:#a6e22e">Types</span>[<span style="color:#a6e22e">types</span>.<span style="color:#a6e22e">TBOOL</span>], <span style="color:#a6e22e">x</span>, <span style="color:#a6e22e">nilValue</span>)
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">b</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">s</span>.<span style="color:#a6e22e">endBlock</span>()
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">b</span>.<span style="color:#a6e22e">Kind</span> = <span style="color:#a6e22e">ssa</span>.<span style="color:#a6e22e">BlockIf</span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">b</span>.<span style="color:#a6e22e">SetControl</span>(<span style="color:#a6e22e">cmp</span>)
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">b</span>.<span style="color:#a6e22e">Likely</span> = <span style="color:#a6e22e">ssa</span>.<span style="color:#a6e22e">BranchUnlikely</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">bThen</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">s</span>.<span style="color:#a6e22e">f</span>.<span style="color:#a6e22e">NewBlock</span>(<span style="color:#a6e22e">ssa</span>.<span style="color:#a6e22e">BlockPlain</span>)
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">bElse</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">s</span>.<span style="color:#a6e22e">f</span>.<span style="color:#a6e22e">NewBlock</span>(<span style="color:#a6e22e">ssa</span>.<span style="color:#a6e22e">BlockPlain</span>)
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">bAfter</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">s</span>.<span style="color:#a6e22e">f</span>.<span style="color:#a6e22e">NewBlock</span>(<span style="color:#a6e22e">ssa</span>.<span style="color:#a6e22e">BlockPlain</span>)
</span></span><span style="display:flex;"><span>	<span style="color:#f92672">...</span>
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">switch</span> <span style="color:#a6e22e">n</span>.<span style="color:#a6e22e">Op</span>() {
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">case</span> <span style="color:#a6e22e">ir</span>.<span style="color:#a6e22e">OLEN</span>:
</span></span><span style="display:flex;"><span>		<span style="color:#a6e22e">s</span>.<span style="color:#a6e22e">vars</span>[<span style="color:#a6e22e">n</span>] = <span style="color:#a6e22e">s</span>.<span style="color:#a6e22e">load</span>(<span style="color:#a6e22e">lenType</span>, <span style="color:#a6e22e">x</span>)
</span></span><span style="display:flex;"><span>	<span style="color:#f92672">...</span>
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">s</span>.<span style="color:#a6e22e">variable</span>(<span style="color:#a6e22e">n</span>, <span style="color:#a6e22e">lenType</span>)
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>该函数的作用是是获取 map 或chan 的内存地址，并以零偏移量引用其结构布局，就像 <code>unsafe.Pointer(uintptr(unsafe.Pointer(s))</code> 一样，返回第一个字面字段的值。</p>
<p>那为什么要获取结构体的第一个字段的值呢，应该是和 map 和 chan 的基础数据结构有关：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-golang" data-lang="golang"><span style="display:flex;"><span><span style="color:#66d9ef">type</span> <span style="color:#a6e22e">hmap</span> <span style="color:#66d9ef">struct</span> {
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">count</span>     <span style="color:#66d9ef">int</span> 
</span></span><span style="display:flex;"><span>  <span style="color:#f92672">...</span>
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">type</span> <span style="color:#a6e22e">hchan</span> <span style="color:#66d9ef">struct</span> {
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">qcount</span>   <span style="color:#66d9ef">uint</span>    
</span></span><span style="display:flex;"><span>	<span style="color:#f92672">...</span>
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>是因为 map 和 chan 的基础数据结构的第一个字段就表示长度，自然也就通过计算偏移值来获取了。</p>
<p>其他的数据类型，大家可以继续深入代码，再细看就好了。主要还是枚举多同类的数据类型，接着调用相应的方法。</p>
<h2 id="总结">总结</h2>
<p>每次我们看到内置函数时，总会下意识的以为是在 runtime 内实现的。看不到 runtime 内的实现方法，又会以为是通过注解 link 的方式来解决的。</p>
<p>但需要注意，其实还有像 len 内置函数这种直接编译器转换的，这也是一种不错的优化方式。</p>
<h2 id="参考">参考</h2>
<ul>
<li><a href="https://tpaschalis.github.io/golang-len">https://tpaschalis.github.io/golang-len</a></li>
<li><a href="https://stackoverflow.com/questions/28204831/how-do-os-len-and-make-functions-work">https://stackoverflow.com/questions/28204831/how-do-os-len-and-make-functions-work</a></li>
</ul>


                                        
                                        
                                        
                                        <div class="rp4wp-related-posts">
                                            <h3>相关文章</h3>
                                            <ul>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/news-slices-maps/">Go 提案：增加泛型版 slices 和 maps 新包</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/delve/">一个 Demo 学会使用 Go Delve 调试</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/gdb/">学会使用 GDB 调试 Go 代码</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/117-build/">时隔 3 年，Go1.17 增强构建约束！</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/memory-model/">Go 内存模型：happens-before 原则</a>
                                                    </div>
                                                </li>
                                                
                                            </ul>
                                        </div>
                                        
                                        
                                    </div>

                                    
                                    
                                    

                                    
                                    <div class="post-meta">
                                        
                                        
                                        <div class="post-tags">
                                            <ul>
                                            
                                            <li>
                                                <a href="/tags/go" title="View all posts tagged match">go</a>
                                            </li>
                                            
                                            </ul>
                                        </div>
                                        
                                        
                                        <nav class="further-reading">
                                            
                                            <div class="previous">
                                                <span>&lt;&lt; Prev</span>
                                                <a href="https://www.lican.asia/posts/posts/go/news-slices-maps/"
                                                    rel="prev">Go 提案：增加泛型版 slices 和 maps 新包</a> </div>
                                            
                                            
                                            <div class="next">
                                                <span>Next >></span>
                                                <a href="https://www.lican.asia/posts/posts/go/plugin/">Go 插件系统，一个凉了快半截的特性？</a> 
                                            </div>
                                            
                                        </nav>
                                    </div>
                                    
                                    

                                    
                                    
                                    

                                </div>
                            </article>
                        </div>
                    </div>
                </section>
                <aside class="sidebar sidebar-primary" id="sidebar-primary" role="complementary">
    <h1 class="screen-reader-text">Sidebar</h1>
    

    
    
    <section id="text-2" class="widget widget_text">
        <div class="textwidget">
            
            <div id="profile">
                <div id="profile_picture"><img src="https://www.lican.asia/logo/logo.png"></div>
                <div id="profile_intro">
                    <p><span class="name">Lican</span></p>
                    <p class="intro">全栈开发者，爱好造轮子。</p>
                </div>
            </div>
            
            <p>
                <script type="text/javascript">
                    (function ($) {
                        $(document).ready(function () {
                            var menuPrimaryContainer = $('#menu-primary-container');
                            var profile = $('#text-2');
                            $('#toggle-navigation').click(function () {
                                if (menuPrimaryContainer.hasClass('open')) {
                                    profile.removeClass('open');
                                } else {
                                    profile.addClass('open');
                                }
                            });
                        });
                    })(jQuery);
                </script>
            </p>
        </div>
    </section>
    
    
    
    
    
    <section id="text-5" class="widget widget_text">
        <h2 class="widget-title">开源项目</h2>
        <div class="textwidget">
            <div id="projects" style="line-height: 22px;">
                
                <a href="https://github.com/idoubi/gonews"
                    target="_blank">gonews</a>: &nbsp;Daily news for golang<br>
                
                <a href="https://github.com/idoubi/sql2struct"
                    target="_blank">sql2struct</a>: &nbsp;Generate go struct according to SQL<br>
                
                <a href="https://github.com/idoubi/goz"
                    target="_blank">goz</a>: &nbsp;Request library used in golang<br>
                
        </div>
    </section>
    
    

    
    
    
    
    <section id="qrcode" class="widget widget_media_image">
        <h2 class="widget-title">微信公众号</h2>
        <img width="258" height="258"
            src="https://www.lican.asia/wechat/lican.png"
            class="image wp-image-5514  attachment-full size-full" alt=""
            style="max-width: 100%; height: auto;"
            sizes="(max-width: 258px) 100vw, 258px">
    </section>
    
    

    
    
    

    
    
    

    
    
    
    
</aside>
            </div>
        </div>

        <footer id="site-footer" class="site-footer" role="contentinfo">
    <div class="max-width">
    </div>
    <div class="footer">
        <div id="footercontent">
            © lican.asia All rights reserved<br/>
            Built with Hugo Theme <a href="https://github.com/idoubi/hugo-theme-period" target="_blank">Period</a>
        </div>
    </div>
</footer>

<script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?e8351b6d4626d5881d439ea1f6184baa";
      var s = document.getElementsByTagName("script")[0]; 
      s.parentNode.insertBefore(hm, s);
    })();
</script>
    
    
    </div>
    
</body>

</html>